package guzb.cnblogs.security.industrydemo.auth.restful;

import guzb.cnblogs.security.industrydemo.auth.AuthorityService;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;

import java.util.function.Supplier;

/**
 * 自定义的基于uri的权限校验
 */
public class MyUriAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {

    private AuthorityService authorityService;

    public MyUriAuthorizationManager(AuthorityService authorityService) {
        this.authorityService = authorityService;
    }

    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext authorizeContext) {
        String uri = authorizeContext.getRequest().getRequestURI();
        if (authorityService.currentUserCanAccess(uri, authorizeContext.getRequest().getMethod())) {
            return new AuthorizationDecision(true);
        }
        return new AuthorizationDecision(false);
    }
}
